//
//  MSPictureDetailVC.m
//  MS
//
//  Created by Yuan on 13-2-27.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#define KBottomToolBarHeight 30
#define kAvatarWidth 40
#define TOPVIEW_LABEL_HEIGHT(content) [content sizeWithFont:FONT_NORMAL constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap].height

#import "ImageScrollView.h"
#import "MSPictureDetailVC.h"
#import "TTTAttributedLabel.h"
#import "UIButton+WebCache.h"
#import "UIColor+ColorUtils.h"
#import <QuartzCore/QuartzCore.h>

#import "MSUserHomeVC.h"

static inline NSRegularExpression * NameRegularExpression() {
    static NSRegularExpression *_nameRegularExpression = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _nameRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"^\\w+" options:NSRegularExpressionCaseInsensitive error:nil];
    });
    
    return _nameRegularExpression;
}

static inline NSRegularExpression * ParenthesisRegularExpression() {
    static NSRegularExpression *_parenthesisRegularExpression = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _parenthesisRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"\\([^\\(\\)]+\\)" options:NSRegularExpressionCaseInsensitive error:nil];
    });
    
    return _parenthesisRegularExpression;
}

@interface MSPictureDetailVC ()<UIScrollViewDelegate,UIActionSheetDelegate,TTTAttributedLabelDelegate>
{
@private
    
    UIButton *avatarBtn;
    
    UIScrollView *mainScrollView;
    
    UIView *topDesView;
    
    UIView *bottomToolBar;
    
    NSMutableArray *allItems;
    
    NSMutableArray *pagesArray;
    
    NSUInteger currentPage ;

    NSUInteger totalPages;
}

@property(nonatomic,retain)UIView *topDesView;

@property(nonatomic,retain)UIView *bottomToolBar;

@property(nonatomic,retain)UIScrollView *mainScrollView;

@property(nonatomic,retain) NSMutableArray *allItems;

@property(nonatomic,retain) NSMutableArray *pagesArray;

@property (nonatomic) TTTAttributedLabel *desLbl;

- (void)loadScrollViewWithPage:(int)page;

@end

@implementation MSPictureDetailVC
@synthesize delegate;
@synthesize mainScrollView = _mainScrollView;
@synthesize allItems = _allItems;
@synthesize pagesArray = _pagesArray;
@synthesize desLbl = _desLbl;
@synthesize topDesView = _topDesView;
@synthesize bottomToolBar = _bottomToolBar;


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:LOADMOREIMAGES object:nil];
    self.mainScrollView = nil;
    self.allItems = nil;
    self.pagesArray = nil;
}

-(void)viewDidUnload
{
    [super viewDidUnload];

    HYLog(@"释放内存....");
    
    [_pagesArray removeAllObjects];
    
    [self.mainScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
    self.mainScrollView = nil;    
}

- (void)didReceiveMemoryWarning
{
    HYLog(@"内存不足了....");
    //如果在当前页面就不会重写loadview和viewdidload
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (id)initWithImages:(NSArray *)imgs currentIndex:(NSInteger)index;
{
    self = [super init];
    if (self) {
        
        _allItems = [[NSMutableArray alloc] initWithArray:imgs];
        
        _pagesArray = [[NSMutableArray alloc]init];
                
        for(SInt16 i = 0 ; i < [_allItems count];i++)
        {
            [_pagesArray addObject:[NSNull null]];
        }
        
        currentPage = index;
        
        totalPages = [_allItems count];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMoreImagesFinished:) name:LOADMOREIMAGES object:nil];
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    
    self.view.backgroundColor = [UIColor blackColor];

    CGRect appFrame = [UIScreen mainScreen].applicationFrame;
    
    self.mainScrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    self.mainScrollView.delegate = self;
    self.mainScrollView.pagingEnabled = YES;
    self.mainScrollView.backgroundColor = [UIColor clearColor];
    self.mainScrollView.contentSize = CGSizeZero;
    self.mainScrollView.showsVerticalScrollIndicator = NO;
    self.mainScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.mainScrollView];
    
    
    CGRect  toolbarFrame = appFrame;
    toolbarFrame.size.height = KBottomToolBarHeight;
    toolbarFrame.origin.y = appFrame.size.height - toolbarFrame.size.height*2;
    self.bottomToolBar = [[UIView alloc]initWithFrame:toolbarFrame];
    [self.bottomToolBar setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:self.bottomToolBar];
    
    UIImage *backimg = [UIImage imageNamed:@"shower_detailimage_back"];

    CGFloat offset_x = 10;
    CGFloat item_space = 15;
    CGFloat btn_width = backimg.size.width;
    
    UIButton *backBtn = [MSTool createButton:CGRectMake(offset_x, 0,btn_width, backimg.size.height) action:@selector(back:) delegate:self];
    [backBtn setImage:backimg forState:UIControlStateNormal];
    [self.bottomToolBar addSubview:backBtn];
    
    offset_x+= (btn_width + 3*item_space);
    
    UIImage *likeimg = [UIImage imageNamed:@"shower_detailimage_like"];
    UIButton *likeBtn = [MSTool createButton:CGRectMake(offset_x,0, likeimg.size.width, likeimg.size.height) action:@selector(likePicture:) delegate:self];
    [likeBtn setImage:likeimg forState:UIControlStateNormal];
    [self.bottomToolBar addSubview:likeBtn];
    
    offset_x+= (btn_width + item_space);
    
    UIImage *favimg = [UIImage imageNamed:@"shower_detailimage_fav"];
    UIButton *favBtn = [MSTool createButton:CGRectMake(offset_x,0, favimg.size.width, favimg.size.height) action:@selector(favoritePicture:) delegate:self];
    [favBtn setImage:favimg forState:UIControlStateNormal];
    [self.bottomToolBar addSubview:favBtn];
    
    offset_x+= (btn_width + item_space);
    
    UIImage *commentimg = [UIImage imageNamed:@"shower_detailimage_comment"];
    UIButton *commentBtn = [MSTool createButton:CGRectMake(offset_x, 0, btn_width, commentimg.size.height) action:@selector(commentPicture:) delegate:self];
    [commentBtn setImage:commentimg forState:UIControlStateNormal];
    [self.bottomToolBar addSubview:commentBtn];
    
    offset_x+= (btn_width + item_space);

    
    UIImage *msgimg = [UIImage imageNamed:@"shower_detailimage_msg"];
    UIButton *msgBtn = [MSTool createButton:CGRectMake(offset_x, 0, btn_width, msgimg.size.height) action:@selector(privateMessage:) delegate:self];
    [msgBtn setImage:msgimg forState:UIControlStateNormal];
    [self.bottomToolBar addSubview:msgBtn];
    
    offset_x+= (btn_width + item_space);
    
    UIImage *shareimg = [UIImage imageNamed:@"shower_detailimage_share"];
    UIButton *shareBtn = [MSTool createButton:CGRectMake(offset_x, 0, btn_width, shareimg.size.height) action:@selector(sharePicture:) delegate:self];
    [shareBtn setImage:shareimg forState:UIControlStateNormal];
    [self.bottomToolBar addSubview:shareBtn];
    
    avatarBtn = [MSTool createButton:CGRectMake(toolbarFrame.size.width - 1.6*kAvatarWidth,toolbarFrame.origin.y - 1.4*kAvatarWidth,kAvatarWidth,kAvatarWidth) action:@selector(userHomePage:) delegate:self];
    avatarBtn.layer.cornerRadius = 2.0f;
    avatarBtn.layer.masksToBounds = YES;
    avatarBtn.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1.0].CGColor;
    avatarBtn.layer.borderWidth = 0.6;
    [avatarBtn setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
    [self.view addSubview:avatarBtn];
    
    _topDesView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, toolbarFrame.size.width,44)];
    [_topDesView setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.3]];
    [self.view addSubview:_topDesView];
    
    CGFloat des_offset  = 10;
    self.desLbl = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(des_offset,des_offset, toolbarFrame.size.width-2*des_offset, 44)];
    self.desLbl.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.desLbl.delegate = self;
    self.desLbl.font = FONT_NORMAL;
    self.desLbl.backgroundColor = [UIColor clearColor];
    self.desLbl.textColor = [UIColor whiteColor];
    self.desLbl.lineBreakMode = UILineBreakModeWordWrap;
    self.desLbl.numberOfLines = 0;
    
    NSMutableDictionary *mutableLinkAttributes = [NSMutableDictionary dictionary];
    [mutableLinkAttributes setObject:(id)[[UIColor colorWithString:@"#f376a0"] CGColor] forKey:(NSString*)kCTForegroundColorAttributeName];
    [mutableLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
    self.desLbl.linkAttributes = mutableLinkAttributes;
    
    self.desLbl.highlightedTextColor = [UIColor yellowColor];
    self.desLbl.verticalAlignment = TTTAttributedLabelVerticalAlignmentTop;
    [_topDesView addSubview:self.desLbl];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES ];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    [self setTitle:HYLocalizedString(@"照片详细") showBackButton:YES];
    
    [self loadScrollViewWithPage:currentPage];
    
    self.mainScrollView.contentSize = CGSizeMake(self.mainScrollView.frame.size.width * totalPages, self.mainScrollView.frame.size.height);
    
    CGPoint point =  CGPointMake(self.mainScrollView.frame.size.width*currentPage, 0);
    [self.mainScrollView setContentOffset:point];
            
    [self refreshUI];
}

-(void)refreshUI
{
    NSDictionary *item = [_allItems objectAtIndex:currentPage];
    [avatarBtn setImageWithURL:[NSURL URLWithString:[item objectForKey:@"avatar"]] forState:UIControlStateNormal];
    
    if ([[item objectForKey:@"content"] length]>0)
    {
        NSString *content  = [NSString stringWithFormat:@"%@: %@",[item objectForKey:@"user_name"],[item objectForKey:@"content"]];
        [self setDesText:content];
        CGFloat topVHeight = TOPVIEW_LABEL_HEIGHT(content)+20;
        CGFloat offset_y = (self.topDesView.frame.origin.y<0)?-topVHeight:0;
        [self.topDesView setFrame:CGRectMake(0,offset_y, self.view.frame.size.width,topVHeight)];
    }
    else
    {
        [self.desLbl setText:@""];
        UIViewSetFrameHeight(self.desLbl,0);
        UIViewSetFrameHeight(_topDesView,0);
    }
}

- (void)loadScrollViewWithPage:(int)page
{
    if (page < 0) return;
    if (page >= totalPages) return;
    ImageScrollView *imageScrollView = [_pagesArray objectAtIndex:page];
    if ((NSNull *)imageScrollView == [NSNull null])
    {
        NSDictionary *item = [_allItems objectAtIndex:page];
        imageScrollView = [[ImageScrollView alloc]initWithFrame:CGRectMake(self.mainScrollView.frame.size.width*page,0,self.mainScrollView.frame.size.width, self.mainScrollView.frame.size.height) url:[item objectForKey:@"src"] target:self];
        [_pagesArray replaceObjectAtIndex:page withObject:imageScrollView];
        [self.mainScrollView addSubview:imageScrollView];
    }
    else
    {
		imageScrollView.zoomScale = 1.0;
    }
}

-(void)handleSingleTap:(UITapGestureRecognizer*)recognizer
{
    CGRect appFrame = [UIScreen mainScreen].applicationFrame;
    
    CGRect avatarFrame = avatarBtn.frame;
    avatarFrame.origin.x =  avatarFrame.origin.x<appFrame.size.width?appFrame.size.width:(appFrame.size.width- 1.6*kAvatarWidth);

    CGRect bottomViewFrame = self.bottomToolBar.frame;
    bottomViewFrame.origin.y = bottomViewFrame.origin.y<appFrame.size.height?appFrame.size.height:(appFrame.size.height - KBottomToolBarHeight*2);
    
    CGRect topViewFrame = self.topDesView.frame;
    topViewFrame.origin.y =  topViewFrame.origin.y<0?0:-topViewFrame.size.height;
    [UIView animateWithDuration:0.2 animations:^(void)
     {
         self.bottomToolBar.frame = bottomViewFrame;
         avatarBtn.frame = avatarFrame;
         self.topDesView.frame = topViewFrame;
     }completion:^(BOOL f){
         
     }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    
    if (((page+1) == totalPages) && [self.delegate respondsToSelector:@selector(requestNewDatas)]) {
//        [self.delegate requestNewDatas];
    }
    
    BOOL isNeedUpdate = (currentPage == page)?NO:YES;

    currentPage = page;
    
    if ([[_allItems objectAtIndex:page] objectForKey:@"user_name"] == nil)
    {
//        [self requestData];
    }
    else
    {
//        [self refreshUI];
    }
    
    [self loadScrollViewWithPage:page - 1];
    
    [self loadScrollViewWithPage:page];
    
    [self loadScrollViewWithPage:page + 1];
    
    for(int i = 0 ;i < [_pagesArray count];i++)
    {
        if(i== currentPage -1 ||i == currentPage || i == currentPage + 1)continue;
        
        ImageScrollView *imageScrollView = [_pagesArray objectAtIndex:i];
        
        if ((NSNull *)imageScrollView != [NSNull null])
        {
            [imageScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [imageScrollView removeFromSuperview];
            [_pagesArray replaceObjectAtIndex:i withObject:[NSNull null]];
            imageScrollView = nil;
        }
    }

    if (isNeedUpdate)[self refreshUI];
    
}

-(void)loadMoreImagesFinished:(NSNotification *)ns
{
    NSArray *arr = [[NSArray alloc]initWithArray:ns.object];
    
    HYLog(@"%@",arr);
}

-(void)userHomePage:(UIButton *)btn
{
    MSUserHomeVC *vc = [[MSUserHomeVC alloc]initWithUID:[NSNumber numberWithInt:0] userName:[[_allItems objectAtIndex:currentPage]objectForKey:@"user_name"]];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)likePicture:(UIButton *)btn
{
    
}

-(void)favoritePicture:(UIButton *)btn
{


}


-(void)commentPicture:(UIButton *)btn
{
    
    
}

-(void)privateMessage:(UIButton *)btn
{
    
    
}

-(void)sharePicture:(UIButton *)btn
{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:HYLocalizedString(@"取消") destructiveButtonTitle:nil otherButtonTitles:
                            HYLocalizedString(@"短信分享"),
                            HYLocalizedString(@"邮件分享"),
                            HYLocalizedString(@"分享到新浪微博"),
                            HYLocalizedString(@"分享到腾讯微博"),
                            HYLocalizedString(@"保存到相册"), nil];
    sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [sheet showInView:self.navigationController.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex)
    {
        return;
    }
    else if(buttonIndex == 0)
    {
//        [self performSelector:@selector(sendEMS) withObject:nil afterDelay:0.0];
    }
    else if(buttonIndex == 1)
    {
//        [self performSelector:@selector(sendEmail) withObject:nil afterDelay:0.0];
    }
    else if(buttonIndex == 2)
    {
//        [self performSelector:@selector(shareToSinaWeiBo) withObject:nil afterDelay:0.0];
    }
    else if(buttonIndex == 3)
    {
//        [self performSelector:@selector(shareToTecentWeiBo) withObject:nil afterDelay:0.0];
    }
    else if(buttonIndex == 4)
    {
//        [self performSelector:@selector(saveToPhotos) withObject:nil afterDelay:0.0];
    }
}


-(void)setDesText:(NSString *)contentString
{
    [self.desLbl setText:contentString afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange stringRange = NSMakeRange(0, [mutableAttributedString length]);
        
        NSRegularExpression *regexp = NameRegularExpression();
        NSRange nameRange = [regexp rangeOfFirstMatchInString:[mutableAttributedString string] options:0 range:stringRange];
        UIFont *boldSystemFont = FONT_NORMAL;
        CTFontRef boldFont = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
        if (boldFont) {
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:nameRange];
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)boldFont range:nameRange];
            CFRelease(boldFont);
        }
        [mutableAttributedString replaceCharactersInRange:nameRange withString:[[mutableAttributedString string] substringWithRange:nameRange]];

//        [mutableAttributedString replaceCharactersInRange:nameRange withString:[[[mutableAttributedString string] substringWithRange:nameRange] uppercaseString]];
        
        regexp = ParenthesisRegularExpression();
        [regexp enumerateMatchesInString:[mutableAttributedString string] options:0 range:stringRange usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
            UIFont *italicSystemFont = FONT_NORMAL;
            CTFontRef italicFont = CTFontCreateWithName((__bridge CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL);
            if (italicFont) {
                [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:result.range];
                [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)italicFont range:result.range];
                CFRelease(italicFont);
                
                [mutableAttributedString removeAttribute:(NSString *)kCTForegroundColorAttributeName range:result.range];
                [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)[[UIColor grayColor] CGColor] range:result.range];
            }
        }];
        
        return mutableAttributedString;
    }];
    
    NSRegularExpression *regexp = NameRegularExpression();
    NSRange linkRange = [regexp rangeOfFirstMatchInString:contentString options:0 range:NSMakeRange(0, [contentString length])];
    NSString *str =  [contentString substringWithRange:linkRange];
    HYLog(@"%@",str);
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://en.wikipedia.org/wiki/%@", [contentString substringWithRange:linkRange]]];
    [self.desLbl addLinkToURL:url withRange:linkRange];
}

#pragma mark - TTTAttributedLabelDelegate
- (void)attributedLabel:(TTTAttributedLabel *)label
   didSelectLinkWithURL:(NSURL *)url
{
    HYLog(@"%@",label.text);
    HYLog(@"%@",url.absoluteString);
    [self userHomePage:avatarBtn];
}


@end
